﻿@using Fluxor.Blazor.Web.Components;
@using SimpleIdServer.IdServer.UI;
@using SimpleIdServer.IdServer.Website.Resources;
@using SimpleIdServer.IdServer.Website.Stores.ClientStore;
@using SimpleIdServer.IdServer.Website.Stores.UserStore;
@inherits FluxorComponent
@inject IState<UpdateUserState> updateUserState
@inject IDispatcher dispatcher

<div>
    <RadzenText TextStyle="TextStyle.Subtitle2" TagName="TagName.H3">@Global.Type</RadzenText>
    <RadzenDropDown Name="Password" Class="w-100"
                    Data=@otpLst
                    TValue="OTPAlgs"
                    @bind-Value=@selectedAlg
                    TextProperty="Name" ValueProperty="Alg"/>
    <RadzenRequiredValidator Component="Password" Text="@Global.PasswordRequired"></RadzenRequiredValidator>
</div>
<RadzenButton class="mt-1" Click="(args) => SubmitPassword()" Variant="Variant.Flat" ButtonType="ButtonType.Submit" ButtonStyle="ButtonStyle.Success" Text="@(updateUserState.Value.IsUpdating ? Global.Saving : Global.Save)" Disabled="@(updateUserState.Value.IsUpdating)" />

@code {
    [Parameter]
    public EventCallback<UserCredential> CredentialSaved { get; set; }
    [Parameter]
    public UserCredential Credential { get; set; }

    record OTPForm
    {
        public OTPAlgs Type { get; set; } = OTPAlgs.TOTP;
    }

    record OTPInfo
    {
        public string Name { get; set; }
        public OTPAlgs Alg { get; set; }
    }

    List<OTPInfo> otpLst = new List<OTPInfo>
    {
        new OTPInfo { Alg = OTPAlgs.TOTP, Name = "TOTP" },
        new OTPInfo { Alg = OTPAlgs.HOTP, Name = "HOTP" }
    };

    OTPAlgs selectedAlg = OTPAlgs.TOTP;

    protected override void OnParametersSet()
    {
        base.OnParametersSet();
        if (Credential == null) return;
        selectedAlg = Credential.OTPAlg.Value;
    }

    async void SubmitPassword()
    {
        var key = KeyGeneration.GenerateRandomKey(20);
        await CredentialSaved.InvokeAsync(new UserCredential { Value = key.ConvertFromBase32(), OTPAlg = selectedAlg });
    }
}